package inits

import (
	"app-webapi/comm/g"
	"context"
	"fmt"
	"github.com/edgexfoundry/app-functions-sdk-go/v2/pkg"
	"github.com/edgexfoundry/app-functions-sdk-go/v2/pkg/interfaces"
	"github.com/edgexfoundry/app-functions-sdk-go/v2/pkg/util"
	"github.com/edgexfoundry/go-mod-bootstrap/v2/di"
	"github.com/gomodule/redigo/redis"
	"os"
	"reflect"
	"strings"
	"time"
)

func AppClient() context.Context {
	ctx, cancel := context.WithCancel(context.Background())
	// turn off secure mode for examples. Not recommended for production
_:
	os.Setenv("EDGEX_SECURITY_SECRET_STORE", "false")

	// 1) First thing to do is to create an instance of the app service and initialize it.
	AppService, ok := pkg.NewAppService(g.ServiceKey)
	g.AppService = AppService
	//g.Logger = AppService.LoggingClient()
	if !ok {
		os.Exit(-1)
	}

	//err := AppService.AddFunctionsPipelineForTopics("AlarmEvent", []string{"/business/alarm"},
	//	printUpperToConsole,
	//)
	//if err != nil {
	//	fmt.Printf("AddFunctionsPipelineForTopic returned error: %s", err.Error())
	//	os.Exit(-1)
	//}

	//订阅总线事件
	if err := AppService.SetFunctionsPipeline(
		func(appCxt interfaces.AppFunctionContext, data interface{}) (bool, interface{}) {
			//判断是否是Event,如果是则发布
			//if event, ok := data.(dtos.Event); ok {
			//	service.WritEdgeXDeviceEventToInfluxDB(event)
			//	err := service.EventPublisher(event)
			//	if err != nil {
			//		g.Logger.Errorf("EventPublisher err,%v", err)
			//	}
			//}

			return true, data
		}); err != nil {
		AppService.LoggingClient().Error("SetFunctionsPipeline failed: " + err.Error())
		os.Exit(-1)
	}

	//获取StoreClient
	go func() {
		for {
			after := time.After(time.Duration(1) * time.Second)
			<-after
			g.Logger.Info("尝试获取Store客户端...")
			container := (*di.Container)(reflect.ValueOf(AppService).Elem().FieldByName("dic").UnsafePointer())
			storeClient := container.Get("github.com/edgexfoundry/app-functions-sdk-go/v2/pkg/interfaces.StoreClient")
			if storeClient != nil {
				g.Store = storeClient.(interfaces.StoreClient)
				g.Logger.Info("成功获取Store客户端")
				g.ResitPool = (*redis.Pool)(reflect.ValueOf(storeClient).Elem().FieldByName("Pool").UnsafePointer())
				g.Logger.Info("成功获取Redis客户端")
				break
			}
		}
	}()

	//开始运行
	go func() {
		err := AppService.MakeItRun()
		g.Logger.Errorf("err,%v", err)
		cancel()
	}()

	return ctx

}

func printUpperToConsole(appContext interfaces.AppFunctionContext, data interface{}) (bool, interface{}) {

	fmt.Printf("kkkkkkk %v", data)
	input, err := util.CoerceType(data)

	if err != nil {
		appContext.LoggingClient().Error(err.Error())
		return false, err
	}

	wait := time.Millisecond * time.Duration(len(input))

	time.Sleep(wait)

	appContext.LoggingClient().Info("PrintToConsole")

	processed := strings.ToUpper(string(input))
	appContext.LoggingClient().Infof("'%s' received %s ago\n", processed, wait.String())

	appContext.SetResponseData([]byte(processed))

	return false, nil
}
